package com.pig4cloud.pigx.common.customize.i18n.util;

import com.pig4cloud.pigx.common.core.util.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import sun.util.locale.BaseLocale;

import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class MessageUtils {
    /**
     * 正则匹配
     */
    private static final Pattern PATTERN = Pattern.compile("(([A-Z|a-z])+(\\.)?)+");

    private MessageUtils() {
    }

    /**
     * 获取消息值
     * 如需要国际化，就处理，否则原样返回
     *
     * @param message 文本消息，如是sys.user.null这样的格式，表示需要处理
     * @param args    参数
     * @return String
     */
    public static String processMessage(String message, Object... args) {
        Matcher matcher = PATTERN.matcher(message);
        if (matcher.matches()) {
            message = MessageUtils.get(message, args);
        }
        return message;
    }

    /**
     * 根据消息键和参数 获取消息 委托给spring messageSource
     *
     * @param msgKey key
     * @param args   参数
     * @return String
     */
    public static String get(String msgKey, Object... args) {
        MessageSource messageSource = SpringContextHolder.getBean("rooMessageSource");
        try {
            return messageSource.getMessage(msgKey, args, LocaleContextHolder.getLocale());
        } catch (Exception e) {
            log.error("message get error:{}", msgKey, e);
            return msgKey;
        }
    }

    public static String get(String msgKey) {
        return get(msgKey, null);
    }

    /**
     * 根据所需语言查找对应语言信息
     *
     * @param msgKey
     * @param locale
     * @param args
     * @return
     */
    public static String getMessageByLocale(String msgKey, Locale locale, Object... args) {
        MessageSource messageSource = SpringContextHolder.getBean("rooMessageSource");
        try {
            return messageSource.getMessage(msgKey, args, locale);
        } catch (Exception e) {
            log.error("message get error:{}", msgKey, e);
            return msgKey;
        }
    }

    /**
     * 根据用户选择语言创建语言环境参数对象
     *
     * @param language 用户选择语言，格式zh_CH
     * @return {@link BaseLocale}
     * @since 2022/9/14 18:13
     */
    public static Locale getLocale(String language) {
        // 如果为空，返回默认的简体中文
        if (Strings.isEmpty(language)) {
            language = "zh_CN";
        }

        String[] split = language.split("_");
        return new Locale(split[0], split[1]);
    }
}
